package com.warmlight.voicepacket.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.OSSRequest;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.google.gson.Gson;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.adapter.Add2NetListAdapter;
import com.warmlight.voicepacket.base.BaseActivity;
import com.warmlight.voicepacket.data.PlaydeatalData;
import com.warmlight.voicepacket.data.RecommendFeed;
import com.warmlight.voicepacket.data.UserCenterData;
import com.warmlight.voicepacket.data.eventbus.CollectMoreAudio;
import com.warmlight.voicepacket.data.eventbus.CollectSingleAudio;
import com.warmlight.voicepacket.data.eventbus.NotifyMyPlaylist;
import com.warmlight.voicepacket.data.eventbus.TeaseRelease;
import com.warmlight.voicepacket.http.Callback;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.utils.FileUtils;
import com.warmlight.voicepacket.utils.JSONUtils;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.utils.ShareCollectCallBackUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import okhttp3.Call;

import static com.warmlight.voicepacket.db.VoicePacketDBHelper.AUDIO_ID;

public class Add2NetListActivity extends BaseActivity {

    //音频数据
    private RecommendFeed.DataBean.ListBean mData;
    private TextView tv_add_list;
    //本地数据库播放列表
//    private List<FloatPlayListData> mPlayListData;
//    private List<DBFloatPlaylist> mPlayListData;
    private ListView lv_local_list;
    private Add2NetListAdapter mAdapter;
    private ArrayList<String> mList;
    private ArrayList<PlaydeatalData.DataBean.ListBean> mType2List;
    private int addType = 0;
    private List<UserCenterData.ListBean> list;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add2list);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            if (bundle.containsKey("audio_id")) {
                //收藏的单个
                addType = 0;
                RecommendFeed.DataBean.ListBean audioData = (RecommendFeed.DataBean.ListBean) getIntent().getSerializableExtra(AUDIO_ID);
                if (audioData != null) {
                    mData = audioData;
                }
            } else if (bundle.containsKey("my_cover")) {
                //从本地播单从来的
                addType = 1;
                mList = (ArrayList<String>) bundle.getSerializable("my_cover");
                if (mList == null) {
                    finish();
                }
            }else if (bundle.containsKey("net_cover")){
                //网络播单里来的
                addType = 2;
                mType2List = (ArrayList<PlaydeatalData.DataBean.ListBean>) bundle.getSerializable("net_cover");
                if (mType2List == null) {
                    finish();
                }
            }else if (bundle.containsKey("mine_audio")){
                //本地的自己制作音频
                addType = 3;
                RecommendFeed.DataBean.ListBean audioData = (RecommendFeed.DataBean.ListBean) getIntent().getSerializableExtra("mine_audio");
                if (audioData != null) {
                    mData = audioData;
                }
            }
        }


        //获取用户的数据
        String userCenter = SPUtils.getString(SPUtils.USER_CENTER);
        if (!TextUtils.isEmpty(userCenter)){
            UserCenterData userCenterData = new Gson().fromJson(userCenter, UserCenterData.class);
            list = userCenterData.getList();
            if (list == null){
                list = new ArrayList<>();
            }
        }else{
            list = new ArrayList<>();
        }

//        mPlayListData = DBFloatPlayListDaoHelp.loadAll(getThis());

        //TODO 查询本地列表并显示
//        List<FloatPlayListData> datalist = DBHelper.getInstance(getThis()).queryAllList();
//        List<DBFloatPlaylist> datalist = DBFloatPlayListDaoHelp.loadAll(getThis());

        lv_local_list = (ListView) findViewById(R.id.lv_local_list);
        mAdapter = new Add2NetListAdapter(getThis(),list);
        lv_local_list.setAdapter(mAdapter);
        lv_local_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
                    UserCenterData.ListBean listBean = list.get(i);
                if (addType == 0) {
                    addType(listBean);
                }else if (addType == 1){

                }else if (addType == 2){
                    addType(listBean);
                }else if (addType == 3){
                    showProgressDialog("音频上传中。。。");
//                    UserCenterData.ListBean listBean = list.get(i);
                    saveToAli(mData,listBean);
                }


            }
        });

        findViewById(R.id.iv_grey).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        tv_add_list = (TextView) findViewById(R.id.tv_add_list);
        tv_add_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                DBHelper.getInstance(getThis()).addList(new FloatPlayListData("李云龙","20", TestData.mImagePath2));
//                DBHelper.getInstance(getThis()).addList(new FloatPlayListData("李云龙2","220", TestData.mImagePath3));
//                DBHelper.getInstance(getThis()).queryListDataByID("0");
                if (addType == 0) {
                    Intent intent = new Intent(getThis(), CreateNetPlaylistActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("AudioData", mData);
                    intent.putExtras(bundle);
                    getThis().startActivity(intent);
                }else if (addType == 1){
                    Intent intent = new Intent(getThis(), CreateNetPlaylistActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("audio_list",mList);
                    intent.putExtras(bundle);
                    getThis().startActivity(intent);
                }else if (addType == 2){
                    Intent intent = new Intent(getThis(), CreateNetPlaylistActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("net_list",mType2List);
                    intent.putExtras(bundle);
                    getThis().startActivity(intent);
                }else if (addType == 3){
                    Intent intent = new Intent(getThis(), CreateNetPlaylistActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("mine_audio", mData);
                    intent.putExtras(bundle);
                    getThis().startActivity(intent);
                }

                finish();
            }
        });
    }

    private void addType(final UserCenterData.ListBean listBean){
        showProgressDialog("");
        final JSONArray jsonArray = new JSONArray();
        if (addType == 0){
            JSONObject jsonObject = new JSONObject();
            try {
                if (TextUtils.equals("2",mData.getType())){
                    jsonObject.put("title", mData.getTitle());
                    jsonObject.put("url", mData.getUrl());
                    jsonObject.put("duration", "0");
                    jsonObject.put("cover_name", mData.getCover_name());
                }else {
                    jsonObject.put("id", mData.getId());
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArray.put(jsonObject);
        }else if (addType == 2){
            for (int i=0;i<mType2List.size();i++){
                PlaydeatalData.DataBean.ListBean listBean1 = mType2List.get(i);
                String type = listBean1.getType();

                JSONObject jsonObject = new JSONObject();
                try {
                    if (TextUtils.equals("2",type)){
                        jsonObject.put("title", listBean1.getTitle());
                        jsonObject.put("url", listBean1.getUrl());
                        jsonObject.put("duration", "0");
                        jsonObject.put("cover_name", listBean1.getCover_name());
                    }else{
                        jsonObject.put("id",listBean1.getId());
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                jsonArray.put(jsonObject);

            }

        }


        String url = HttpConfig.SYNC_DATA;
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("audio_list",jsonArray.toString());
        treeMap.put("member_cover_name",listBean.getName());
        treeMap.put("auth_key", SPUtils.getLoginAuthKey());
        HttpClient.post(url, treeMap, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideProgressDialog();
                        showToast("收藏失败，请重试");
                    }
                });
            }

            @Override
            public void onResponse(Call call, String response)   {
//                String post = response.body().string();
                if (!TextUtils.isEmpty(response)){
                    ArrayList<Map<String, String>> listMapByJson = JSONUtils.getListMapByJson(response);
                    if (listMapByJson.size()>0){
                        Map<String, String> map = listMapByJson.get(0);
                        if (TextUtils.equals("200",map.get("code"))){

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    hideProgressDialog();
                                    EventBus.getDefault().post(new NotifyMyPlaylist("net"));
                                    if (addType == 0){
                                        EventBus.getDefault().post(new CollectSingleAudio(mData.getId()));
                                        ShareCollectCallBackUtils.collectCallBack(mData.getId(),"1",listBean.getId());
                                    }else{
                                        EventBus.getDefault().post(new CollectMoreAudio(jsonArray.toString()));
                                        List<String> ids = new ArrayList<>();
                                        for (int i=0;i<mType2List.size();i++){
                                           ids.add(mType2List.get(i).getId());
                                        }
                                        ShareCollectCallBackUtils.collectCallBack(ids,"1",listBean.getId());
                                    }
                                    showToast("收藏成功");
                                    finish();
                                }
                            });

                        }else{

                        }
                    }
                }
            }
        });

    }



    private ProgressDialog progressDialog;
    private void showProgressDialog(String msg){
        if (progressDialog == null){
            progressDialog = new ProgressDialog(this,android.R.style.Theme_Material_Light_Dialog_Alert);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
        }
        if (TextUtils.isEmpty(msg)){
            progressDialog.setMessage("加载数据中");
        }else{
            progressDialog.setMessage(msg);
        }

        progressDialog.show();
    }

    private void hideProgressDialog(){
        if (progressDialog != null){
            if (progressDialog.isShowing()){
                progressDialog.dismiss();
            }
        }
    }





    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
    }
//    @Override
//    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
//        super.startActivityForResult(intent, requestCode, options);
//        overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
//    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_out);
    }


    private void saveToAli(final RecommendFeed.DataBean.ListBean bean, final UserCenterData.ListBean listBean){


        OSS mOss = getOSS();
//        DBFloatPlayListDetail detail = dbFloatPlayListDetails.get(i);
        String localFile = bean.getUrl();
        File file = new File(localFile);
        if (!file.exists()) {
            Log.w("AsyncPutImage", "FileNotExist");
            Log.w("LocalFile", localFile);
            hideProgressDialog();
            showToast("音频文件损坏，请重试");
            return;
        }
        final String object = HttpConfig.localAudio() + file.getName();
        if (object.equals("")) {
            Log.w("AsyncPutImage", "ObjectNull");
            hideProgressDialog();
            showToast("音频文件损坏，请重试");
            return;
        }

        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(HttpConfig.bucket, object, localFile);
        put.setCRC64(OSSRequest.CRC64Config.YES);
//        if (mCallbackAddress != null) {
//            // 传入对应的上传回调参数，这里默认使用OSS提供的公共测试回调服务器地址
//            put.setCallbackParam(new HashMap<String, String>() {
//                {
//                    put("callbackUrl", mCallbackAddress);
//                    //callbackBody可以自定义传入的信息
//                    put("callbackBody", "filename=${object}");
//                }
//            });
//        }

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                int progress = (int) (100 * currentSize / totalSize);
//                mDisplayer.updateProgress(progress);
//                mDisplayer.displayInfo("上传进度: " + String.valueOf(progress) + "%");

            }
        });

        OSSAsyncTask task = mOss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");

                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());

//                long upload_end = System.currentTimeMillis();
//                OSSLog.logDebug("upload cost: " + (upload_end - upload_start) / 1000f);
//                mDisplayer.uploadComplete();
//                mDisplayer.displayInfo("Bucket: " + mBucket
//                        + "\nObject: " + request.getObjectKey()
//                        + "\nETag: " + result.getETag()
//                        + "\nRequestId: " + result.getRequestId()
//                        + "\nCallback: " + result.getServerCallbackReturnBody());

                String alifile = HttpConfig.ali + object;
                saveToNet(alifile,bean,listBean);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                String info = "";
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    info = clientExcepion.toString();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                    info = serviceException.toString();
                }
//                mDisplayer.uploadFail(info);
//                mDisplayer.displayInfo(info);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideProgressDialog();
                        showToast("文件上传失败，请重试");
                    }
                });

            }
        });
    }

    private void saveToNet(String alifile, final RecommendFeed.DataBean.ListBean bean, UserCenterData.ListBean listBean){
        String json = toJson(alifile,bean);

        String url = HttpConfig.SYNC_DATA;
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("audio_list",json);
        treeMap.put("member_cover_name",listBean.getName());
        treeMap.put("auth_key", SPUtils.getLoginAuthKey());
        HttpClient.post(url, treeMap, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideProgressDialog();
                        showToast("上传音频失败，请重试");
                    }
                });
            }

            @Override
            public void onResponse(Call call, String response)  {
//                String post = response.body().string();
                if (!TextUtils.isEmpty(response)){
                    ArrayList<Map<String, String>> listMapByJson = JSONUtils.getListMapByJson(response);
                    if (listMapByJson.size()>0){
                        Map<String, String> map = listMapByJson.get(0);
                        if (TextUtils.equals("200",map.get("code"))){

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    hideProgressDialog();
                                    EventBus.getDefault().post(new NotifyMyPlaylist("net"));
                                    EventBus.getDefault().post(new TeaseRelease());
                                    showToast("上传音频成功");
                                    String url1 = bean.getUrl();
                                    FileUtils.delete(url1);//删除文件
                                    finish();
                                }
                            });

                        }else{

                        }
                    }
                }
            }
        });

    }

    /**
     * 增加的type 用于提交本地音频数据同步时区分是文字转语音还是录音。
     * @param alifile
     * @param bean
     * @return
     */
    private String toJson(String alifile, RecommendFeed.DataBean.ListBean bean){
        String duraton = "0";
        String url = bean.getUrl();
        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepare();
            duraton = (mediaPlayer.getDuration()*1000)+"";
        } catch (IOException e) {
            e.printStackTrace();
            if (!TextUtils.isEmpty(bean.getDuration())) {
                duraton = bean.getDuration();
            }
        }

        JSONArray jsonArray = new JSONArray();

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("title",bean.getTitle());
            jsonObject.put("url",alifile);
            jsonObject.put("duration",duraton);
            jsonObject.put("cover_name",bean.getCover_name());
            jsonObject.put("type",bean.getType());
            String is_open = bean.getIs_open();
            if (!TextUtils.isEmpty(is_open)){
                jsonObject.put("is_open",is_open);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        jsonArray.put(jsonObject);



        return jsonArray.toString();
    }

    private OSS mOss;
    private OSS getOSS(){
        if (mOss == null) {
            String endpoint = HttpConfig.endpoint;
            String stsServer = "STS应用服务器地址，例如http://abc.com";
//推荐使用OSSAuthCredentialsProvider。token过期可以及时更新
            OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(HttpConfig.accessKeyId, HttpConfig.accessKeySecret);
//该配置类如果不设置，会有默认配置，具体可看该类
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
            conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
            conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个
            conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
            mOss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
        }
        return mOss;
    }

}
